package com.guo.boot.study.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @Auther Heart Guo
 * @Date 2021/12/22-14:45
 */
//练习Thread，实现多线程同步下载图片
public class TestThread02 extends Thread{
    private String url;//网络图片地址
    private String name;//保存的文件名
    public TestThread02(String url,String name){
        this.name = name;
        this.url = url;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载的文件名为"+name);
    }

    public static void main(String[] args) {
        TestThread02 t1 = new TestThread02("https://pic3.zhimg.com/v2-a65467bc7377f6e473a58726acee548a_r.jpg","1.jpg");
        TestThread02 t2 = new TestThread02("https://pic3.zhimg.com/v2-ab2de87cf6b2856504a2620ae8ec44d6_r.jpg","2.jpg");
        TestThread02 t3 = new TestThread02("https://pic1.zhimg.com/v2-47c069e2fbdec4cd50293f8b149b2718_r.jpg","3.jpg");

        //同时进行
        t1.start();
        t2.start();
        t3.start();

        //顺序执行
        /*t1.run();
        t2.run();
        t3.run();*/
    }
}

//下载器
class WebDownloader{
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常。downloader方法出现问题");
        }
    }
}